<template>
  <div v-loading="openAnAccountLoading">
    <el-form ref="ruleForm" :model="ruleForm" status-icon :rules="rulesAccount" class="demo-ruleForm">
      <el-form-item :label="$t('登录名')" prop="email">
        <el-input v-model="ruleForm.email" auto-complete="new-password" :placeholder="$t('请输入登录名')" show-word-limit maxlength="100" />
      </el-form-item>
      <el-form-item :label="$t('登录密码')" prop="password">
        <el-input v-model="ruleForm.password" type="password" auto-complete="new-password" :placeholder="passwordMsg" show-word-limit maxlength="100" />
      </el-form-item>
      <el-form-item :label="$t('确认密码')" prop="confirmPassword">
        <el-input v-model="ruleForm.confirmPassword" type="password" autocomplete="off" :placeholder="$t('确认密码')" show-word-limit maxlength="100" />
      </el-form-item>
      <el-form-item :label="$t('客户类型')" prop="status">
        <br>
        <el-checkbox-group v-model="ruleForm.status" @change="checkRadioStatus(ruleForm.status)">
          <el-checkbox label="ZTJJ">{{ $t('现有客户') }}</el-checkbox>
          <el-checkbox label="CBJJ">{{ $t('潜在客户') }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item :label="$t('可见菜单')" prop="menu">
        <br>
        <el-checkbox-group v-model="ruleForm.menu" @change="checkBoxStatus">
          <el-checkbox
            v-for="(dict, index) in menuOptions"
            :key="index"
            :label="dict.dictValue"
          >{{ $t(dict.dictLabel) }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <div class="area-header">
        <span class="area-header-title">{{ $t('可查看基金') }}</span>
      </div>
      <div>
        <el-table v-loading="fundLoading" :data="fundDataList" border>
          <el-table-column :label="$t('基金全称')" prop="fundFullName" align="center" show-overflow-tooltip min-width="120">
            <template slot-scope="scope">
              <router-link
                target="_blank"
                :to="{path:'/fund/fundBasehome',query:{id:scope.row.id}}"
                class="link_a"
                @click.native="recorePath({ fromPath: $route.fullPath, path:'/fund/fundBasehome',query:{id:scope.row.id}})"
              >
                {{ scope.row.fundFullName }}
              </router-link>
            </template>
          </el-table-column>
          <el-table-column :label="$t('基金简称')" prop="fundName" align="center" show-overflow-tooltip min-width="120" />
          <el-table-column :label="$t('基金负责人')" prop="managerName" align="center" show-overflow-tooltip min-width="120" />
          <el-table-column :label="$t('类型')" prop="fundType" align="center" show-overflow-tooltip min-width="120">
            <template slot-scope="scope">
              <span v-show="scope.row.fundType === 'investor'">{{ $t('出资人') }}</span>
              <span v-show="scope.row.fundType === 'intention'">{{ $t('潜在客户') }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-form>
    <el-dialog v-if="showLogDrawer" :title="$t('操作日志')" :visible.sync="showLogDrawer" :close-on-click-modal="false" width="50%" :destory-on-close="true" :lock-scroll="false" custom-class="folderOpen" append-to-body>
      <lpOperationLogList ref="lpOperationLogList" :show-top-title="false" />
    </el-dialog>
    <el-dialog v-if="lpAccountEmailOpen" :title="$t('邮件发送')" :visible.sync="lpAccountEmailOpen" :close-on-click-modal="false" width="50%" :destory-on-close="true" :lock-scroll="false" custom-class="folderOpen" append-to-body>
      <lpAccountEmail ref="lpAccountEmail" @submitAccountStart="submitAccountStart(true)" />
    </el-dialog>
    <div slot="footer" class="dialog-footer" style="text-align: center; margin-top: 10px;">
      <el-button :type="ruleForm.id ? 'success' : 'info'" :disabled="!ruleForm.id" @click="singleSingOn">{{ $t('登录') }}</el-button>
      <el-button :type="ruleForm.id ? 'warning' : 'info'" :disabled="!ruleForm.id" @click="openLogDrawer">{{ $t('日志') }}</el-button>
      <el-button :type="'info'" :disabled="!ruleForm.id" @click="delAccount">{{ $t('注销') }}</el-button>
      <el-button @click="close">{{ $t('取消') }}</el-button>
      <el-button type="primary" :disabled="saveDisabled" @click="submitAccount">{{ $t('保存') }}</el-button>
    </div>
  </div>
</template>

<script>
import lpOperationLogList from '@/views/fund/lpBase/lpOperationLog/lpOperationLogList.vue'
import lpAccountEmail from '@/views/fund/lpBase/lpAccountEmail.vue'
import { delLpAccount, getByLpId, saveAccountUser, verifyThatTheAccountExists } from '@/api/fund/lpBase/lpBase'
import { getToken } from '@/utils/auth'
import { findGrAndJgByLpId } from '@/api/fund/investor/fundInvestor'
export default {
  components: {
    lpOperationLogList,
    lpAccountEmail
  },
  data() {
    var checkPassword = (rule, value, callback) => {
      const that = this.ruleForm
      if (that.id) {
        // 修改
        if (that.password && that.confirmPassword && that.password !== that.confirmPassword) {
          callback(new Error(this.$t('两次密码不一致!')))
        } else {
          callback()
        }
      } else {
        // 新增
        if (!value) {
          return callback()
        } else if (that.password && that.confirmPassword && that.password !== that.confirmPassword) {
          callback(new Error(this.$t('两次密码不一致!')))
        } else {
          callback()
        }
      }
    }
    var checkEmail = (rule, value, callback) => {
      const that = this.ruleForm
      if (!value) {
        return callback(new Error(this.$t('必填信息')))
      } else if (that.email.length < 6) {
        callback(new Error(this.$t('登陆名至少6位')))
      } else {
        verifyThatTheAccountExists(this.ruleForm.email).then(response => {
          // 为空返回true
          if (response.data === false) {
            if (this.emailDisableEmail === that.email) {
              if (that.id !== undefined && that.id !== null && that.id !== '') {
                callback()
              } else {
                callback(new Error(this.$t('账号已存在!')))
              }
            } else {
              callback(new Error(this.$t('账号已存在!')))
            }
          } else {
            callback()
          }
        })
      }
    }
    return {
      // 遮盖层
      loading: false,
      showLogDrawer: false,
      openAnAccountLoading: false,
      menuOptions: undefined,
      fundTypeOption: [],
      lpLoginUrl: undefined,
      passwordMsg: '',
      fundLoading: false,
      fundDataList: [],
      fundDataListBak: [],
      saveDisabled: false,
      rulesAccount: {
        email: [{ required: true, validator: checkEmail,	trigger: 'blur' }],
        password: [{ required: false, validator: checkPassword,	trigger: 'blur' }],
        confirmPassword: [{ required: false, validator: checkPassword,	trigger: 'blur' }],
        menu: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        status: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
      },
      ruleForm: {
        email: '',
        password: '',
        confirmPassword: '',
        status: [],
        menu: ''
      },
      lpAccountEmailOpen: false
    }
  },
  computed: {},
  created() {
    this.getDicts('lp_menu_name').then(response => {
      this.menuOptions = response.data
    })
    this.getDicts('lp_fund_type_option').then(response => {
      this.fundTypeOption = response.data
    })
  },
  methods: {
    init(row) {
      console.log('处理LP账户')
      this.thatRowData = row
      this.passwordMsg = ''
      this.ruleForm.id = ''
      this.ruleForm.password = ''
      this.ruleForm.confirmPassword = ''
      this.ruleForm.status = ['ZTJJ', 'CBJJ']
      this.ruleForm.menu = ''
      this.ruleForm.email = this.thatRowData.客户邮箱 === '--' ? '' : this.thatRowData.客户邮箱
      this.ruleForm.email = this.ruleForm.email === '' ? this.thatRowData.email : this.ruleForm.email
      this.openAnAccountLoading = true
      this.checkRadioStatus(this.ruleForm.status)
      getByLpId(row.客户ID || row.id).then(response => {
        if (response.code === 200) {
          if (response.data !== null) {
            this.lpLoginUrl = response.data.lpUrl
            this.ruleForm.id = response.data.id
            this.ruleForm.lpId = response.data.lpId
            this.ruleForm.email = response.data.userName
            this.ruleForm.status = response.data.status
            if (response.data.menu !== '' && response.data.menu !== null && response.data.menu !== undefined) {
              this.ruleForm.menu = response.data.menu.split(',')
            }
            this.emailDisableEmail = this.ruleForm.email
            this.passwordMsg = this.$t('不修改请留空')
            this.$parent.$parent.openAnAccountTitle = this.$t('LP账户修改')
          } else {
            this.ruleForm.lpId = undefined
            this.emailDisableEmail = undefined
            this.passwordMsg = this.$t('密码为空时,自动生成密码!')
            this.$parent.$parent.openAnAccountTitle = this.$t('LP账户开通')
          }
        }
        this.openAnAccountLoading = false
      })
      // 获取出资人对应的基金
      this.getFundDataList(row.客户ID || row.id)
    },
    // 开通账户
    submitAccount() {
      this.saveDisabled = true
      setTimeout(() => {
        this.saveDisabled = false
      }, 1000)
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          var _this = this
          if (this.ruleForm.id === undefined || this.ruleForm.id === null || this.ruleForm.id === '') {
            this.$confirm(this.$t('账号开通后是否需要为LP发送提醒?'), this.$t('提示'), {
              confirmButtonText: this.$t('发送'),
              cancelButtonText: this.$t('不发送'),
              type: 'warning',
              showClose: false
            }).then(() => {
              _this.toEmailSendingPage(true)
            }).catch(() => {
              this.submitAccountStart(false)
            })
          } else {
            this.$confirm(this.$t('账号修改后是否需要为LP发送提醒?'), this.$t('提示'), {
              confirmButtonText: this.$t('发送'),
              cancelButtonText: this.$t('不发送'),
              type: 'warning',
              showClose: false
            }).then(() => {
              _this.toEmailSendingPage(false)
            }).catch(() => {
              this.submitAccountStart(false)
            })
          }
        } else {
          return false
        }
      })
    },
    // 跳转邮件发送页面
    toEmailSendingPage(isInitPassword) {
      this.lpAccountEmailOpen = true
      this.$nextTick(() => {
        if (isInitPassword) {
          var password = Math.floor(Math.random() * 900000) + 100000
          this.ruleForm.password = password
          this.ruleForm.confirmPassword = password
        }
        this.ruleForm.emailTemp = JSON.parse(JSON.stringify(this.thatRowData.邮箱 || this.thatRowData.客户邮箱))
        this.ruleForm.lpNameTemp = this.thatRowData.客户全称
        this.$refs.lpAccountEmail.init(this.ruleForm, this.thatRowData.客户ID || this.thatRowData.id)
      })
    },
    // 删除账户
    delAccount() {
      var that = this
      this.$confirm(this.$t('是否注销账号?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(function() {
        delLpAccount(that.ruleForm.lpId).then(() => {
          that.msgSuccess(that.$t('注销成功!'))
          that.close()
        }).catch(() => {
          that.msgInfo(that.$t('先创建账户才能执行注销操作!'))
        })
      }).then(() => {
        this.getList()
      })
    },
    submitAccountStart(sendEmail) {
      this.openAnAccountLoading = true
      const data = {
        id: this.ruleForm.id,
        lpId: this.thatRowData.客户ID || this.thatRowData.id,
        userName: this.ruleForm.email,
        password: this.ruleForm.password,
        menu: this.ruleForm.menu.toString(),
        status: this.ruleForm.status,
        sendEmail: sendEmail
      }
      saveAccountUser(data).then(response => {
        if (response.code === 200 && response.data !== null && response.data.code === 200) {
          this.$notify({
            title: this.$t('消息'),
            message: '<span>' + this.$t(response.data.msg) + '</span>',
            dangerouslyUseHTMLString: true,
            type: 'success',
            duration: 30000
          })
          this.close()
        } else {
          this.$notify({
            title: this.$t('警告'),
            message: '<span>' + this.$t(response.data.msg) + '</span>',
            dangerouslyUseHTMLString: true,
            type: 'warning',
            duration: 30000
          })
        }
        this.openAnAccountLoading = false
      })
    },
    // 单点登录
    singleSingOn() {
      window.open(this.lpLoginUrl + '/singleSignOn?managerToken=' + getToken() + '&lpId=' + this.ruleForm.lpId)
    },
    openLogDrawer() {
      this.showLogDrawer = true
      this.$nextTick(() => {
        this.$refs.lpOperationLogList.lpId = this.ruleForm.lpId
        this.$refs.lpOperationLogList.getList()
      })
    },
    // 清空菜单
    checkRadioStatus(status) {
      console.log(status)
      if (status.includes('ZTJJ')) {
        // 字段的 value 就用中文的  传递到Lp的就是 dictValue这个值
        this.ruleForm.menu = ['首页', '分配信息', 'DataRoom', '投资组合', '信息披露', '基金信息', '缴款信息', '公示公告', '问卷调查']
      } else if (status.includes('CBJJ')) {
        this.ruleForm.menu = ['DataRoom', '公示公告', '问卷调查']
      } else {
        this.ruleForm.menu = []
      }

      if (status.includes('ZTJJ') && status.includes('CBJJ')) {
        this.fundDataList = this.fundDataListBak
      } else {
        if (status.includes('ZTJJ')) {
          // 项目列表展示
          this.fundDataList = []
          this.fundDataListBak && this.fundDataListBak.forEach(item => {
            if (item.fundType === 'investor') {
              this.fundDataList.push(item)
            }
          })
        } else if (status.includes('CBJJ')) {
          this.fundDataList = []
          this.fundDataListBak && this.fundDataListBak.forEach(item => {
            if (item.fundType === 'intention') {
              this.fundDataList.push(item)
            }
          })
        } else {
          this.fundDataList = []
        }
      }
    },
    checkBoxStatus() {
      if (!this.ruleForm.status.includes('CBJJ') && !this.ruleForm.status.includes('ZTJJ')) {
        this.ruleForm.menu = []
        this.msgError(this.$t('先选择状态'))
      }
    },
    close() {
      this.openAnAccountLoading = false
      this.$parent.$parent.openAnAccountOpen = false
    },
    // 获取该出资人透过的基金
    getFundDataList(lpId) {
      this.fundDataList = []
      this.fundDataListBak = []
      this.fundLoading = true
      findGrAndJgByLpId(lpId).then(response => {
        this.fundDataList = response.data
        this.fundDataListBak = response.data
        this.fundLoading = false
      }).catch(() => {
        this.fundLoading = false
      })
    }
  }
}
</script>

<style scoped>
</style>
